#include <iostream>
#include <ctime>
#include <cstdlib>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>

#include "SharedMemoryBuffer.h"

int main(int argc, char* argv[]) {
	
	srand(time(NULL));
	try 
	{
		boost::interprocess::shared_memory_object::remove("shared_memory");
		boost::interprocess::shared_memory_object shm(
			boost::interprocess::create_only,
			"shared_memory",
			boost::interprocess::read_write
		);
		shm.truncate(sizeof(SharedMemoryBuffer));

		boost::interprocess::mapped_region region(
			shm,
			boost::interprocess::read_write
		);

		void* regionAddr = region.get_address();

		SharedMemoryBuffer* buffer = new (regionAddr) SharedMemoryBuffer;
	
		while(true)
		{
			// make writing to the buffer and to the console output buffer mutually exclusice
			buffer->writer.wait();
			std::cout << "reading calculated value from buffer: " << buffer->data << std::endl;
			buffer->data = rand();
			//suspend execution
			sleep(1);
			// let the second process, proceed execution after data is written
			buffer->reader.post();
		}
	}
	catch(boost::interprocess::interprocess_exception &e)
	{
		boost::interprocess::shared_memory_object::remove("shared_memory");
		std::cerr << "error occured: " << e.what();
		return 1;
	}
	boost::interprocess::shared_memory_object::remove("shared_memory");

	return 0;
}